import request from '../../services/request';
const app = getApp();

Page({
  data: {
    categories: [],         // [{type: 'senior', name: '初中'}, ...]
    selectedCategory: '',   // 当前选中的分类type
    bookMap: {},            // {senior: [book, book, ...], ...}
    currentBookId: ''      // 当前学习的词书id
  },

  async onLoad() {
    const res = await request.get('/wordbook/list');
    let currentBookId = '';
    if (app.globalData.currentLearningBook) {
      currentBookId = app.globalData.currentLearningBook.bookId;
    }
    if (res.code === 200) {
      const categories = res.data.map(item => ({ type: item.type, name: item.name }));
      const bookMap = {};
      res.data.forEach(item => {
        bookMap[item.type] = item.bookList;
      });
      this.setData({
        categories,
        selectedCategory: categories[0]?.type || '',
        bookMap,
        currentBookId
      });
    }
  },

  onTabChange(e) {
    this.setData({
      selectedCategory: e.detail.value
    });
  },

  async selectBook(e) {
    const book = e.currentTarget.dataset.book;
    if (book.bookId === this.data.currentBookId) return;
    const res = await request.get(`/wordbook/updateCurrent?bookId=${book.bookId}`);
    if (res.code === 200 && res.data === true) {
      if (!app.globalData.currentLearningBook) app.globalData.currentLearningBook = {};
      app.globalData.currentLearningBook.bookId = book.bookId;
      wx.showToast({ title: '切换成功', icon: 'success', duration: 800 });
      setTimeout(() => {
        wx.reLaunch({ url: '/pages/index/index' });
      }, 800);
    }
  }
}); 